import json


class ResponseHandler:
    def __init__(self, captured_responses):
        self.captured_responses = captured_responses

    def capture_obtain_payment_response(self, route, request):
        """
        捕获 obtainPayment 接口的响应并存储到变量中。
        """
        response = route.fetch()
        if response.ok:
            self.captured_responses["obtainPayment"] = response.json()
            route.fulfill(response=response)
        else:
            print(f"Failed to fetch obtainPayment response: {response.status_code} {response.text}")

    def modify_transaction_pay_response(self, route, request):
        """
        修改 transactionPay 接口的响应。
        """
        response = route.fetch()
        original_data = response.json()

        # 修改响应数据
        modified_data = original_data.copy()
        modified_data["result"]["url"] = self.captured_responses["obtainPayment"]["result"]["paySuccessUrl"] + "&doubleSign=0"
        # modified_data["result"]["payUrl"] = "https://www.baidu.com/"

        # 返回修改后的响应
        route.fulfill(
            response=response,
            status=200,
            body=json.dumps(modified_data),
            headers={"Content-Type": "application/json"},
        )
